import 'dart:convert';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/good_list_entity.dart';
import 'package:panda/goods/GoodsDetail.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/SignUtil.dart';

import '../base/Constant.dart';
import '../util/DateUtils.dart';

class ReviewGoodsPage extends StatefulWidget {
  ReviewGoodsPage({Key key}) : super(key: key);

  @override
  _ReviewGoodsPageState createState() => _ReviewGoodsPageState();
}

class _ReviewGoodsPageState extends State<ReviewGoodsPage> {
  EasyRefreshController _controller = new EasyRefreshController();
  var time1 = "", time2 = "", time3 = "", time4 = "", current = "";
  List<GoodsListDataData> goodsList = new List();
  String group_id = "1";
  String token = "";
  int page = 1;
  @override
  void initState() {
    super.initState();
    var today = DateTime.now();
    var fiftyDaysFromNow = today.subtract(new Duration(days: 1));
    time1 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch, format: "MM-dd");
    current = time1;
    fiftyDaysFromNow = today.subtract(new Duration(days: 2));
    time2 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch, format: "MM-dd");
    fiftyDaysFromNow = today.subtract(new Duration(days: 3));
    time3 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch, format: "MM-dd");
    fiftyDaysFromNow = today.subtract(new Duration(days: 4));
    time4 = DateUtils.instance.getFormartData(
        timeSamp: fiftyDaysFromNow.millisecondsSinceEpoch, format: "MM-dd");

    if (APPLIC.userInfoMap != null) {
      group_id = APPLIC.userInfoMap['user_msg']['group_id'].toString();
      getString(TOKEN).then((value) {
        token = value;
        loadList();
      });
    } else {
      loadList();
    }
  }

  loadList() async {
    Map map = new Map();
    // map['cat_id'] = "2";
    map['token'] = token;
    map['p'] = page.toString();
    map['per'] = "10";
    map['date'] = DateTime.now().year.toString() + "-" + current;
    map['sign_type'] = SignType.GET_GOODS_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      GoodsListEntity bannerEntity = new GoodsListEntity.fromJson(userMap);
      setState(() {
        if (page == 1) {
          goodsList.clear();
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(
              success: true, noMore: bannerEntity.data.datas.length == 0);
          if (bannerEntity.data.datas.length == 0) {
            Fluttertoast.showToast(msg: "已加载全部");
          }
        }
        goodsList.addAll(bannerEntity.data.datas);
        setState(() {});
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        physics: new NeverScrollableScrollPhysics(),
        child: Stack(
          children: <Widget>[
            Image.asset(
              "images/bg_review.png",
              fit: BoxFit.fill,
              width: MediaQuery.of(context).size.width,
            ),
            Container(
              width: double.infinity,
              margin: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_20),
                  MediaQueryData.fromWindow(window).padding.top + 15,
                  0,
                  0),
              child: new Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                        child: Icon(
                          Icons.arrow_back_ios,
                          color: black,
                          size: ScreenUtil.getInstance().setHeight(DP_40),
                        ),
                      ),
                      Expanded(child: Center()),
                      Text(
                        '往期回顾',
                        style: TextStyle(
                            color: black,
                            fontSize:
                                ScreenUtil.getInstance().setSp(BIG_FONT_SIZE)),
                      ),
                      Expanded(child: Center()),
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {},
                        child: Icon(
                          Icons.arrow_back_ios,
                          color: Colors.transparent,
                          size: ScreenUtil.getInstance().setHeight(DP_40),
                        ),
                      ),
                    ],
                  ),
                  Container(
                    height: ScreenUtil.getInstance().setHeight(DP_20),
                  ),
                  Container(
                      child: new Row(
                        children: <Widget>[
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                setState(() {
                                  current = time1;
                                  page = 1;
                                  loadList();
                                });
                              },
                              child: Center(
                                child: Column(
                                  children: <Widget>[
                                    Text(time1,
                                        style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(time1 == current
                                                    ? NORMAL_FONT_SIZE
                                                    : SMALL_FONT_SIZE))),
                                    Container(
                                      margin: EdgeInsets.all(
                                          ScreenUtil.getInstance()
                                              .setHeight(DP_10)),
                                      width: DP_20,
                                      height: 2,
                                      color: time1 == current
                                          ? black
                                          : Colors.transparent,
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                setState(() {
                                  current = time2;
                                  page = 1;
                                  loadList();
                                });
                              },
                              child: Center(
                                child: Column(
                                  children: <Widget>[
                                    Text(time2,
                                        style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(time2 == current
                                                    ? NORMAL_FONT_SIZE
                                                    : SMALL_FONT_SIZE))),
                                    Container(
                                      margin: EdgeInsets.all(
                                          ScreenUtil.getInstance()
                                              .setHeight(DP_10)),
                                      width: DP_20,
                                      height: 2,
                                      color: time2 == current
                                          ? black
                                          : Colors.transparent,
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                setState(() {
                                  current = time3;
                                  page = 1;
                                  loadList();
                                });
                              },
                              child: Center(
                                child: Column(
                                  children: <Widget>[
                                    Text(time3,
                                        style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(time3 == current
                                                    ? NORMAL_FONT_SIZE
                                                    : SMALL_FONT_SIZE))),
                                    Container(
                                      margin: EdgeInsets.all(
                                          ScreenUtil.getInstance()
                                              .setHeight(DP_10)),
                                      width: DP_20,
                                      height: 2,
                                      color: time3 == current
                                          ? black
                                          : Colors.transparent,
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                          Expanded(
                            child: GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                setState(() {
                                  current = time4;
                                  page = 1;
                                  loadList();
                                });
                              },
                              child: Center(
                                child: Column(
                                  children: <Widget>[
                                    Text(time4,
                                        style: TextStyle(
                                            color: black,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(time4 == current
                                                    ? NORMAL_FONT_SIZE
                                                    : SMALL_FONT_SIZE))),
                                    Container(
                                      margin: EdgeInsets.all(
                                          ScreenUtil.getInstance()
                                              .setHeight(DP_10)),
                                      width: DP_20,
                                      height: 2,
                                      color: time4 == current
                                          ? black
                                          : Colors.transparent,
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      height: ScreenUtil.getInstance().setHeight(DP_50 + 5)),
                  Container(
                      height: MediaQuery.of(context).size.height -
                          MediaQueryData.fromWindow(window).padding.top -
                          ScreenUtil.getInstance().setHeight(DP_20) -
                          ScreenUtil.getInstance().setHeight(70),
                      child: EasyRefresh(
                        controller: _controller,
                        enableControlFinishLoad: true,
                        enableControlFinishRefresh: true,
                        header: MaterialHeader(),
                        footer: MaterialFooter(),
                        onLoad: () {
                          page++;
                          loadList();
                        },
                        onRefresh: () {
                          page = 1;
                          loadList();
                        },
                        child: ListView.builder(
                          padding: EdgeInsets.only(top: 0),
                          shrinkWrap: true,
                          itemCount: goodsList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return renderRow(context, index);
                          },
                        ),
                      ))
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget renderRow(BuildContext context, int index) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setHeight(0),
            ScreenUtil.getInstance().setHeight(DP_20),
            ScreenUtil.getInstance().setHeight(DP_20),
            0),
        decoration: BoxDecoration(
            color: black,
            borderRadius: BorderRadius.circular(
                ScreenUtil.getInstance().setHeight(DP_10))),
        child: Material(
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10)),
          color: black,
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Stack(
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.only(
                        topRight: Radius.circular(
                            ScreenUtil.getInstance().setHeight(DP_10)),
                        topLeft: Radius.circular(
                            ScreenUtil.getInstance().setHeight(DP_10))),
                    child: CachedNetworkImage(
                        imageUrl: Api.ImgBaseUrl + goodsList[index].img,
                        width: MediaQuery.of(context).size.width -
                            ScreenUtil.getInstance().setHeight(DP_40),
                        fit: BoxFit.fill,
                        height: (MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_40)) /
                            2.2),
                  ),
                  Offstage(
                    child: Container(
                        alignment: Alignment.center,
                        child: Text(
                          '已售罄',
                          style: TextStyle(color: black, fontSize: 17),
                        ),
                        color: Color.fromARGB(125, 0, 0, 0),
                        width: MediaQuery.of(context).size.width -
                            ScreenUtil.getInstance().setHeight(DP_40),
                        height: (MediaQuery.of(context).size.width -
                                ScreenUtil.getInstance().setHeight(DP_40)) /
                            2.2),
                    offstage: (int.parse(goodsList[index].sales_volume) +
                                int.parse(goodsList[index].virtual_volume)) >=
                            int.parse(goodsList[index].num)
                        ? false
                        : true,
                  )
                ],
              ),
              Padding(
                padding: EdgeInsets.fromLTRB(
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_15),
                    ScreenUtil.getInstance().setHeight(DP_8)),
                child: Text(
                  goodsList[index].goods_name,
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                      color: black),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Row(children: <Widget>[
                Expanded(
                    child: Column(children: <Widget>[
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_15),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_15),
                        ScreenUtil.getInstance().setHeight(DP_15)),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: <Widget>[
                        Text('团购价' + MONEY,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(MINI_FONT_SIZE),
                                color: mainColor)),
                        Text(
                            goodsList[index].price.toString()
                                ,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE),
                                color: mainColor)),
                        // Expanded(
                        //   child: Text(''),
                        //   flex: 1,
                        // ),
                          Text('   市场价$MONEY',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE),
                              color:black_99
                                  )),
                      Text(
                          goodsList[index].old_price.toString()
                              ,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE-3),
                              color: black
                                  )),
                    
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_15),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_15),
                        ScreenUtil.getInstance().setHeight(DP_15)),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        SizedBox(
                          width: ScreenUtil.getInstance().setHeight(25) *
                                  goodsList[index].avatars.length.toDouble() +
                              12,
                          child: Stack(
                              alignment: AlignmentDirectional.topStart,
                              children: buildAvatar(goodsList[index].avatars)),
                        ),
                        Container(
                            width: ScreenUtil.getInstance().setHeight(DP_15)),
                        Text(
                            (int.parse(goodsList[index].sales_volume) +
                                        int.parse(
                                            goodsList[index].virtual_volume))
                                    .toString() +
                                '人已购',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE - 2),
                                color: Colors.black45)),
                        // Expanded(
                        //   child: Center(),
                        // ),
                      ],
                    ),
                  )
                ])),
                (int.parse(goodsList[index].sales_volume) +
                            int.parse(goodsList[index].virtual_volume)) >=
                        int.parse(goodsList[index].num)
                    ? new Container(
                        color: Colors.grey[300],
                        margin: EdgeInsets.only(right: 10),
                        padding: EdgeInsets.fromLTRB(10, 5, 10, 2),
                        child: Text("已售罄",
                            style: TextStyle(
                                color: black,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE))),
                      )
                    : Column(children: <Widget>[
                        new Container(
                          height: ScreenUtil.getInstance().setWidth(DP_40),
                          margin: EdgeInsets.only(right: 10),
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(DP_160),
                          decoration: new BoxDecoration(
                              color: Colors.black,
                              border: Border.all(width: 1, color: mainColor),
                              borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(3),
                                  topRight: Radius.circular(3))),
                          child: new Padding(
                            padding: EdgeInsets.only(left: 10.0, right: DP_10),
                            child: new Text(
                              (int.parse(goodsList[index].sales_volume) +
                                          int.parse(goodsList[index]
                                              .virtual_volume)) >=
                                      int.parse(goodsList[index].num)
                                  ? "售罄"
                                  : "限" + goodsList[index].num + "份",
                              style: new TextStyle(
                                  color: mainColor,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE - 2)),
                            ),
                          ),
                        ),
                        new Container(
                          height: ScreenUtil.getInstance().setWidth(DP_40),
                          margin: EdgeInsets.only(right: 10),
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(DP_160),
                          decoration: new BoxDecoration(
                              color: mainColor,
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(3),
                                  bottomRight: Radius.circular(3))),
                          child: new Padding(
                            padding: EdgeInsets.only(left: 10.0, right: DP_10),
                            child: new Text(
                              "立即购买",
                              style: new TextStyle(
                                  color: Colors.black,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE - 2)),
                            ),
                          ),
                        )
                      ])
              ])
            ],
          ),
          elevation: 1,
        ),
      ),
      onTap: () {
        if ((int.parse(goodsList[index].sales_volume) +
                int.parse(goodsList[index].virtual_volume)) >=
            int.parse(goodsList[index].num)) {
          Fluttertoast.showToast(msg: '亲宝贝已经售馨，下次早抢哦！');

          return;
        }
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return GoodsDetailPage(
            goods_id: goodsList[index].goods_id,
            img: goodsList[index].img,
          );
        }));
      },
    );
  }

  buildAvatar(List<GoodsListDataDatasTag> avatars) {
    List<Widget> list = new List();
    list.add(ClipOval(
      child: CachedNetworkImage(
          imageUrl: Api.ImgBaseUrl + avatars[0].avatar,
          width: ScreenUtil.getInstance().setHeight(35),
          height: ScreenUtil.getInstance().setHeight(35)),
    ));
    for (int i = 1; i < avatars.length; i++) {
      list.add(
        Positioned(
          left: ScreenUtil.getInstance().setHeight(25) * i.toDouble(),
          child: ClipOval(
            child: CachedNetworkImage(
                imageUrl: Api.ImgBaseUrl + avatars[i].avatar,
                width: ScreenUtil.getInstance().setHeight(35),
                height: ScreenUtil.getInstance().setHeight(35)),
          ),
        ),
      );
    }
    return list;
  }
}
